<script setup>
import { ref, onBeforeMount, nextTick } from 'vue'
import { Edit, Delete } from '@element-plus/icons-vue'
import {
  employeeRolePageService,
  employeeRoleAddService,
  employeeRoleUpdateService,
  employeeRoleDeleteMultipleService
} from '@/api/employeeRole'
import { permissionSelectAllService } from '@/api/permission'
import { menuSelectAllService } from '@/api/menu'

// 查询条件表单数据
const formInline = ref({
  currentPage: 1,
  pageSize: 10,
  role: '',
  keyword: '',
  level: '',
  description: ''
})

const permissionsInfo = ref([])

const menusInfo = ref([])

// 条件查询表单对象
const queryForm = ref()

const loading = ref(false)

// 管理员权限信息表格数据
const tableData = ref()

// 定义分页条参数
const pages = ref({
  total: 0
})

const getEmployeeRolesPage = async () => {
  loading.value = true
  await employeeRolePageService(formInline.value).then((response) => {
    pages.value = response.data
    tableData.value = pages.value.records
    loading.value = false
  })
}

// 组件挂载前加载数据
onBeforeMount(async () => {
  formInline.value.currentPage = 1
  formInline.value.pageSize = 10

  await permissionSelectAllService().then((response) => {
    permissionsInfo.value = response.data
  })

  await menuSelectAllService().then((response) => {
    menusInfo.value = response.data
  })

  await getEmployeeRolesPage()
})

// 多选处理
const multipleSelection = ref()

const handleSelectionChange = (rows) => {
  multipleSelection.value = rows
}

const onSizeChange = (size) => {
  //每页条数变化了，重新从第一页渲染即可
  formInline.value.currentPage = 1
  formInline.value.pageSize = size
  getEmployeeRolesPage()
}

const onCurrentChange = (pagenum) => {
  // 更新当前页
  formInline.value.currentPage = pagenum
  getEmployeeRolesPage()
}

// 修改、增加弹窗
const dialogVisible = ref(false)

// 修改、增加表单数据
const formModel = ref({
  id: '',
  role: '',
  keyword: '',
  level: '',
  description: '',
  noPermission: false,
  permissionIds: [],
  menuIds: []
})

// 修改、增加表单对象
const dialogForm = ref()

// 表单规则
const queryRules = {
  level: [
    { pattern: /^\d*$/, message: '权限角色等级格式错误', trigger: 'blur' }
  ]
}

const editRules = {
  role: [{ required: true, message: '权限角色不能为空', trigger: 'blur' }],
  keyword: [
    { required: true, message: '权限角色关键字不能为空', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '权限角色等级不能为空', trigger: 'blur' },
    { pattern: /^\d*$/, message: '权限角色等级格式错误', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '权限角色描述不能为空', trigger: 'blur' }
  ],
  permissionIds: [
    {
      required: true,
      message: '具体权限不能为空',
      trigger: 'blur'
    }
  ],
  menuIds: [
    {
      required: true,
      message: '界面菜单不能为空',
      trigger: 'blur'
    }
  ]
}

const changeNoPermission = () => {
  if (formModel.value.noPermission) {
    formModel.value.permissionIds = []
    editRules.permissionIds[0].required = false
  } else {
    editRules.permissionIds[0].required = true
  }
}

// 查询提交
const getEmployeeRolesQuery = async () => {
  await queryForm.value.validate()
  formInline.value.currentPage = 1
  getEmployeeRolesPage()
}

// 添加逻辑
const onAddEmployeeRole = () => {
  formModel.value = {}

  formModel.value.noPermission = false
  editRules.permissionIds[0].required = true

  dialogVisible.value = true

  nextTick(() => {
    dialogForm.value.resetFields()
  })
}

//编辑逻辑
const onEditEmployeeRole = (row) => {
  /* 当你使用{ ...row }这样的语法创建一个新对象时，它会将row对象中的所有属性复制到新对象中。
  如果formModel中有一个属性b，而row中没有b属性，那么在执行formModel.value = { ...row }后，
  formModel中的b属性会变为undefined。 */

  // formModel.value = Object.assign({}, formModel.value, row)
  formModel.value = { ...row, noPermission: false }
  formModel.value.permissionIds = row.permissions.map((permission) => {
    return permission.id
  })

  formModel.value.menuIds = row.menus.map((menu) => {
    return menu.id
  })

  // 无具体权限视为无权限
  if (row.permissions.length === 0) {
    formModel.value.noPermission = true
    formModel.value.permissionIds = []
    editRules.permissionIds[0].required = false
  }

  dialogVisible.value = true

  nextTick(() => {
    dialogForm.value.clearValidate()
  })
}

const onSubmit = async () => {
  await dialogForm.value.validate()
  if (formModel.value.id) {
    await employeeRoleUpdateService(formModel.value)
  } else {
    await employeeRoleAddService(formModel.value)
  }

  ElMessage.success(
    formModel.value.id
      ? '修改管理员权限角色信息成功'
      : '添加管理员权限角色信息成功'
  )
  // 弹层关闭
  dialogVisible.value = false
  // 重新渲染
  getEmployeeRolesPage()
  // TODO 实时响应变化
}

const onDeleteEmployeeRole = async (row) => {
  await ElMessageBox.confirm('你确认删除该管理员权限角色信息吗？', '温馨提示', {
    type: 'warning',
    confirmButtonText: '确认',
    cancelButtonText: '取消'
  })
  await employeeRoleDeleteMultipleService(row.id)
  ElMessage.success('删除成功')
  getEmployeeRolesPage()
}

const onDeleteEmployeeRoles = async () => {
  const tips = multipleSelection.value.map(
    (row) => '<i>' + row.role + ' : ' + row.keyword + '</i><br />'
  )
  const ids = multipleSelection.value.map((row) => row.id)
  await ElMessageBox.confirm(
    '你确认删除<br/>' + tips.join('') + '吗？',
    '温馨提示',
    {
      type: 'warning',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      dangerouslyUseHTMLString: true
    }
  )
  await employeeRoleDeleteMultipleService(ids)
  ElMessage.success('删除成功')
  getEmployeeRolesPage()
}
</script>

<template>
  <div class="root">
    <el-container class="list">
      <el-header>
        <el-form
          :inline="true"
          :model="formInline"
          :rules="queryRules"
          ref="queryForm"
        >
          <el-form-item label="权限角色" style="width: 160px">
            <el-input
              v-model="formInline.role"
              placeholder="权限角色"
              clearable
            />
          </el-form-item>

          <el-form-item label="权限角色关键字" style="width: 240px">
            <el-input
              v-model="formInline.keyword"
              placeholder="权限角色关键字"
              clearable
            />
          </el-form-item>

          <el-form-item label="权限角色等级" style="width: 220px">
            <el-input
              v-model="formInline.level"
              placeholder="权限角色等级"
              clearable
            />
          </el-form-item>

          <el-form-item label="权限角色描述" style="width: 220px">
            <el-input
              v-model="formInline.description"
              placeholder="权限角色描述"
              clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="getEmployeeRolesQuery">
              查询
            </el-button>

            <el-button type="primary" @click="onAddEmployeeRole">
              添加管理员权限角色信息
            </el-button>

            <el-button type="primary" @click="onDeleteEmployeeRoles">
              删除选中管理员角色权限信息
            </el-button>
          </el-form-item>
        </el-form>
      </el-header>

      <el-main>
        <el-table
          :data="tableData"
          style="width: 100%; height: 90%"
          table-layout="auto"
          highlight-current-row
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column fixed type="selection" width="50" />

          <el-table-column fixed label="权限角色" prop="role" min-width="160" />

          <el-table-column
            label="权限角色关键字"
            prop="keyword"
            min-width="240"
          />

          <el-table-column label="权限等级" prop="level" min-width="160" />

          <el-table-column
            label="权限角色描述"
            prop="description"
            width="200"
            show-overflow-tooltip
          />

          <el-table-column
            label="具体权限"
            prop="permission"
            width="200"
            show-overflow-tooltip
          >
            <template #default="{ row }">
              {{
                row.permissions.map((permission) => {
                  return permission.name
                })
              }}
            </template>
          </el-table-column>

          <el-table-column prop="createTime" label="创建时间" min-width="200" />

          <el-table-column
            prop="createEmployeeName"
            label="创建者"
            min-width="90"
          />

          <el-table-column prop="updateTime" label="更新时间" min-width="200" />

          <el-table-column
            prop="updateEmployeeName"
            label="更新者"
            min-width="90"
          />

          <el-table-column fixed="right" label="操作" width="120">
            <template #default="{ row }">
              <el-button
                :icon="Edit"
                circle
                plain
                type="primary"
                @click="onEditEmployeeRole(row)"
              ></el-button>

              <el-button
                :icon="Delete"
                circle
                plain
                type="danger"
                @click="onDeleteEmployeeRole(row)"
              ></el-button>
            </template>
          </el-table-column>

          <template #empty>
            <el-empty :image-size="200" description="暂无数据" />
          </template>
        </el-table>

        <el-pagination
          v-model:current-page="formInline.currentPage"
          v-model:page-size="formInline.pageSize"
          :page-sizes="[5, 10, 20]"
          :page-counter="7"
          layout="prev, pager, next, total, ->, jumper, sizes"
          background
          :total="pages.total"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          style="margin-top: 10px; justify-content: center"
        />
      </el-main>
    </el-container>

    <el-dialog
      v-model="dialogVisible"
      :title="
        formModel.id ? '修改管理员权限角色信息' : '添加管理员权限角色信息'
      "
      top="10vh"
      width="50%"
    >
      <el-form
        :model="formModel"
        :rules="editRules"
        label-width="130px"
        style="padding: 0"
        ref="dialogForm"
        :hide-required-asterisk="true"
      >
        <el-form-item label="id" v-if="formModel.id ? true : false">
          <el-input v-model="formModel.id" disabled />
        </el-form-item>

        <el-form-item label="权限角色" prop="role">
          <el-input
            v-model="formModel.role"
            placeholder="请输入权限角色"
            clearable
          />
        </el-form-item>

        <el-form-item label="权限角色关键字" prop="keyword">
          <el-input
            v-model="formModel.keyword"
            placeholder="请输入权限角色关键字"
            clearable
          />
        </el-form-item>

        <el-form-item label="权限角色等级" prop="level">
          <el-input
            v-model="formModel.level"
            placeholder="请输入权限角色等级"
            clearable
          />
        </el-form-item>

        <el-form-item label="权限角色描述" prop="description">
          <el-input
            v-model="formModel.description"
            placeholder="请输入权限角色描述"
            clearable
          />
        </el-form-item>

        <el-form-item label="权限角色具体权限" prop="permissionIds">
          <div>
            <el-checkbox-group v-model="formModel.permissionIds">
              <el-tooltip
                v-for="permission in permissionsInfo"
                :key="permission.id"
                effect="light"
                :content="permission.description"
                placement="bottom"
                :hide-after="0"
              >
                <el-checkbox
                  :label="permission.name"
                  :value="permission.id"
                  border
                  size="default"
                  style="margin: 0 10px 5px 0"
                  :disabled="formModel.noPermission"
                />
              </el-tooltip>
            </el-checkbox-group>

            <el-checkbox
              v-model="formModel.noPermission"
              label="无具体权限"
              value="无具体权限"
              border
              size="default"
              @change="changeNoPermission"
            />
          </div>
        </el-form-item>

        <el-form-item label="权限角色界面菜单" prop="menuIds">
          <el-checkbox-group v-model="formModel.menuIds">
            <el-tooltip
              v-for="menu in menusInfo"
              :key="menu.id"
              effect="light"
              :content="menu.description"
              placement="bottom"
              :hide-after="0"
            >
              <el-checkbox
                :label="menu.name"
                :value="menu.id"
                border
                size="default"
                style="margin: 0 10px 5px 0"
              />
            </el-tooltip>
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.root {
  height: 100%;
}

.list {
  height: 100%;

  .el-header {
    height: auto;
    margin: 10px 0;
    padding: 0;

    .el-form {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;

      .el-form-item {
        justify-content: end;
        align-items: center;
        margin: 0;
        margin-bottom: 10px;
      }
    }
  }

  .el-main {
    height: 100%;
    padding: 0;
  }

  .el-dialog {
    .el-form {
      margin: 10px 40px 10px 0;
    }
  }
}
</style>
